import { Message } from 'view-design'

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

/**
 * @Author tangyuhui
 * @Description 下划线转驼峰
 * @Date 2021-05-01 21:02:36 Saturday
 */

export function camelCase(str) {
  return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

/**
 * @Author tangyuhui
 * @Description 判断是否是数字字符串
 * @Date 2021-05-01 21:02:10 Saturday
 */
export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

/**
 * @Author Tangyuhui
 * @Description 浏览器支持检查
 * @Date 2019-11-01 10:15:05 星期五
 */
export function supportUserAgent() {
  let browser
  const userAgent = navigator.userAgent
  if (userAgent.indexOf('MicroMessenger') > -1) {
    browser = 'MicroMessenger'
  } else if (userAgent.indexOf('360') > -1) {
    browser = '360'
  } else if (userAgent.indexOf('QQ') > -1) {
    browser = 'QQ'
  } else if (userAgent.indexOf('LBBROWSER') > -1) {
    browser = 'LBBROWSER'
  } else if (userAgent.indexOf('Chrome') > -1) {
    browser = 'Chrome'
  } else if (/CriOS/i.test(userAgent) && /iphone|ipod|ipad/i.test(userAgent)) {
    browser = 'Chrome'
  } else if (userAgent.indexOf('Opera') > -1) {
    browser = 'Opera'
  } else if (userAgent.indexOf('Firefox') > -1) {
    browser = 'Firefox'
  } else if (userAgent.indexOf('Safari') > -1) {
    browser = 'Safari'
  } else if (!!window.ActiveXObject || 'ActiveXObject' in window) {
    browser = 'IE'
  } else {
    browser = 'unknown'
  }
  return browser === 'QQ' || browser === 'Chrome'
}

/**
 * @Author Tangyuhui
 * @Description 找到字符串中第n个匹配的位置
 * @Date 2019-11-26 14:24:33 Tuesday
 */
export function findStrNindex(str, cha, num) {
  var x = str.indexOf(cha)
  for (var i = 0; i < num; i++) {
    x = str.indexOf(cha, x + 1)
  }
  return x
}

/**
 * @Author Tangyuhui
 * @Description 去除首尾空格
 * @Date 2019-11-26 14:24:12 Tuesday
 */
export function trim(value) {
  if (value && typeof value === 'string') {
    return value.replace(/(^\s*)|(\s*$)/g, '')
  } else {
    return value
  }
}

/**
 * @Author Tangyuhui
 * @Description 截取图片
 * @Date 2019-11-26 14:24:04 Tuesday
 */
export function sliceImage(src, style = {}, onComplete) {
  const image = new Image()
  image.crossOrigin = 'anonymous'
  image.src = src
  image.onload = function() {
    // 取出中间段图片背景
    const canvas = document.createElement('canvas')
    canvas.width = style.width
    canvas.height = style.height
    canvas.getContext('2d').drawImage(image, style.x, style.y, style.width, style.height, 0, 0, style.width, style.height)
    onComplete(canvas.toDataURL('image/jpg'))
  }
}

/**
 * @Author Tangyuhui
 * @Description 格式化金额
 * @Date 2019-11-26 16:28:23 Tuesday
 */
/* eslint-disable */
export function formatCurrency(value) {
    if (!value || isNaN(value)) {
        return value
    }
    let hasNegative = false
    /**如果以负数开头 */
    value = value.toString()
    if (value.indexOf('-') === 0) {
        hasNegative = true
        value = value.substr(1)
    }
    let n = 2
    value = parseFloat((value + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
    var l = value.split('.')[0].split('').reverse(),
        r = value.split('.')[1]
    let t = ''
    for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? ',' : '')
    }
    let money = t.split('').reverse().join('') + '.' + r
    if (hasNegative) {
        return '-' + money
    } else {
        return money
    }
}

/**
 * @Author Tangyuhui
 * @Description 格式化浮点数
 * @Date 2019-11-26 16:28:47 Tuesday
 */
export function formatFloat(number, precision) {
    return Math.round(+number + 'e' + precision) / Math.pow(10, precision);
}


/**
 * @Author Tangyuhui
 * @Description 四舍五入保留2位小数（不够位数，则用0替补）
 * @Date 2019-11-26 16:31:36 Tuesday
 */
export const keepTwoDecimalFull = num => {
    var result = parseFloat(num)
    if (isNaN(result)) {
        return result
    }
    result = Math.round(num * 10000) / 10000
    var s_x = result.toString()
    var pos_decimal = s_x.indexOf('.')
    if (pos_decimal < 0) {
        pos_decimal = s_x.length
        s_x += '.'
    }
    while (s_x.length <= pos_decimal + 4) {
        s_x += '0'
    }
    return s_x
}


/**
 * @Description:  判断文件类型
 * @author tangyuhui
 * @date 2021/4/9 11:10 下午
*/
export const fnFileType = function (strs, str) {
    if (strs.split('.')[strs.split('.').length - 1].indexOf(str) !== -1) {
        return true
    } else {
        return false
    }
}

/**
 * @Description: 格式化文件大小
 * @author tangyuhui
 * @date 2021/4/9 11:10 下午
*/
export function renderSize(value) {
    if (null == value || value == '') {
        return "0 Bytes";
    }
    var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
    var index = 0,
        srcsize = parseFloat(value);
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    var size = srcsize / Math.pow(1024, index);
    //  保留的小数位数
    size = size.toFixed(2);
    return size + unitArr[index];
}

/**
 * @Author Tangyuhui
 * @Description 获取没有后缀名的文件名
 * @Date 2019-11-26 16:39:24 Tuesday
 */
export function getFileNameNoSuffix(data) {
    return data.substring(0, data.lastIndexOf("."));
}

/**
 * @Author Tangyuhui
 * @Description 拆分字母和字符
 * @Date 2019-11-26 16:39:24 Tuesday
 */
export function splitDigitAndChar(data) {
    var reg = /(\d*)(.*)/;
    reg.test(data);
    return {
        digit: RegExp.$1,
        char: RegExp.$2
    }
}

/**
 * @Author Tangyuhui
 * @Description 格式化展示数字区间值
 * @Date 2019-11-26 16:39:24 Tuesday
 */
export  function formatRangeValue(leftVal, rightVal) {
    if (isNotEmpty(leftVal) && isNotEmpty(rightVal)) {
        if (leftVal === rightVal) {
            return leftVal
        } else {
            return `${leftVal}~${rightVal}`
        }
    } else if (isNotEmpty(leftVal)) {
        return '≥' + leftVal
    } else if (isNotEmpty(rightVal)) {
        return '≤' + rightVal
    } else {
        return '暂无'
    }
}

/**
 * @Author Tangyuhui
 * @Description 数组交换位置
 * @Date 2019-11-26 16:39:24 Tuesday
 */
export function swapArr(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
}

/**
 * @Author Tangyuhui
 * @Description array转map
 * @Date 2019-11-26 16:39:24 Tuesday
 */
export function arrayToMap(originArray, fieldCode) {
    const result = originArray.reduce((obj, item) => {
        obj[item[fieldCode]] = item
        return obj
    }, {})
    return result
}



/**
 * @Author Tangyuhui
 * @Description 比较数组是否相等
 * @Date 2019-11-26 16:39:24 Tuesday
 */
export function arrayEquals(base, array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (base.length != array.length)
        return false;

    for (var i = 0, l = base.length; i < l; i++) {
        // Check if we have nested arrays
        if (base[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!arrayEquals(base[i], array[i]))
                return false;
        } else if (!isObjEqual(base[i], array[i])) {
            return false;
        }
    }
    return true;
}

/**
 * @Author Tangyuhui
 * @Description 下载
 * @Date 2019-12-19 15:46:29 星期四
 */
export function downloadURI(uri, name) {
    var link = document.createElement('a');
    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}


/**
 * @Author Tangyuhui
 * @Description toast弹窗
 * @Date 2020-01-16 16:37:37 星期四
 */
export function showError(error) {
  if (error && error.message) {
    Message.error(error.message)
  } else {
    Message.error(error)
  }
}

/**
 * @Author Tangyuhui
 * @Description toast弹窗
 * @Date 2020-01-16 16:37:37 星期四
 */
export function showSuccess(msg) {
    Message.success(msg)
}

/**
 * @Author tangyuhui
 * @Description 表单重置
 * @Date 2021-05-01 21:01:22 Saturday
 */
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

/**
 * @Author tangyuhui
 * @Description 是否为空
 * @Date 2021-05-01 21:01:13 Saturday
 */
export function isNotEmpty(value){
  return value!==undefined && value!==null && value!==''
}

/**
 * @Description: 通过url路径获取文件名
 * @author tangyuhui
 * @date 2021/5/10 10:42 下午
*/
export function getFileNameByUrl(url){
  const reg =new RegExp(".+/(.+)$",'g')
  reg.test(url)
  const match = RegExp.$1
  return match && decodeURI(match)
}

export const sleep = async function(delay, cb) {
  let promise = () => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, delay);
    });
  };
  await promise();
  if (cb && typeof cb === "function") {
    cb();
  }
  return true;
};
